package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    private StockMapper stockMapper;

	@Override
	public boolean isAsync() {
		return false;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean handle(TransHandlerContext context) {
		// 将context转换为已经有数据的CreateOrderContext（向下转型）
		CreateOrderContext createOrderContext = (CreateOrderContext) context;

		// 获取购物车商品信息
		List<CartProductDto> dtoList = createOrderContext.getCartProductDtoList();

		// 获取生成订单商品的idList  此时为null
		List<Long> productIds = createOrderContext.getBuyProductIds();

		if (CollectionUtils.isEmpty(productIds)) {
//			// 为空  进行赋值
//			for (CartProductDto cartProductDto : dtoList) {   将购物车CartProductDto中的productId,赋值给productIds
//				productIds.add(cartProductDto.getProductId());
//			}
			// 实现的功能与上边一样
			productIds = dtoList.stream().map(u -> u.getProductId()).collect(Collectors.toList());
			// 排序：根据大小，进行排序
			productIds.sort(Long::compareTo);
			// 锁定库存：防止出现问题（根据商品id，查询库存信息；然后，锁定住；拿到一个库存的list；）
			List<Stock> stockList = stockMapper.findStocksForUpdate(productIds);

//			if (CollectionUtils.isEmpty(stockList)) throw new BizException("库存未被初始化！");  //假如库存为空，则抛出异常
			if (CollectionUtils.isEmpty(stockList)) throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(),"库存未被初始化！");  //假如库存为空，则抛出异常

//			if (stockList.size() != productIds.size()) throw new BizException("部分商品库存未被初始化！");  //假如库存的数量和商品id的数量不匹配，抛出异常
			if (stockList.size() != productIds.size()) throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(),"部分商品库存未被初始化！");  //假如库存的数量和商品id的数量不匹配，抛出异常

			// 扣减库存
			for (CartProductDto cartProductDto : dtoList) {
				Long productId = cartProductDto.getProductId();
				Long productNum = cartProductDto.getProductNum();

				// 限购和库存不足
				for (Stock stock : stockList) {
					if (stock.getItemId().equals(productId)) {
						// 库存不足
						if (stock.getStockCount() < productNum) throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(),"库存不足！");
						// 限购
						if (productNum > stock.getRestrictCount()) throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(),"您的购买数量超过限购数！");
					}
					break;
				}

				Stock stock = new Stock();
				stock.setItemId(productId);
				stock.setLockCount(productNum.intValue());
				stock.setStockCount(-productNum);

				// 库存数量始终大于0
				try {
					stockMapper.updateStock(stock);
				} catch (Exception e) {
					throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(),OrderRetCode.DB_EXCEPTION.getMessage());
				}
			}
		}
		return true;
	}
}